package com.cgtong.android.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;

import com.ashokvarma.bottomnavigation.BottomNavigationBar;
import com.ashokvarma.bottomnavigation.BottomNavigationItem;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.cgtong.android.App;
import com.cgtong.android.R;
import com.cgtong.android.base.BaseActivity;
import com.cgtong.android.db.UserAccount;
import com.cgtong.android.event.LoadUserInfoEvent;
import com.cgtong.android.fragment.CityDynamicFragment;
import com.cgtong.android.fragment.HomeFragment;
import com.cgtong.android.fragment.MeFragment;
import com.cgtong.android.fragment.ShowEverybodyFragment;
import com.cgtong.android.http.ConstantManager;
import com.umeng.analytics.MobclickAgent;

import org.simple.eventbus.EventBus;
import org.simple.eventbus.Subscriber;

import butterknife.BindView;

/**
 * 主页框架Activity
 * Created by Sky.Bing on 2017/10/17.
 */
public class MainActivity extends BaseActivity implements BottomNavigationBar.OnTabSelectedListener {

    @BindView(R.id.bottom_bar)
    public BottomNavigationBar mBottomNavigationBar;

    private int curIndex;
    private int beforeIndex;
    private Fragment[] mFragments = new Fragment[4];
    private FragmentManager mFragmentManager;

    @Override
    public int getLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    public void initData() {
//        setSwipeBackEnable(false);

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 注册对象
        mFragmentManager = getSupportFragmentManager();
        EventBus.getDefault().register(this);
        SPUtils.getInstance().put(ConstantManager.FIRST_TOKEN_VALIDATE, false);
        initFragment();
        initBottomBar();
    }

    private void initFragment() {
        mFragments[0] = HomeFragment.newInstance();
        mFragments[1] = CityDynamicFragment.newInstance();
        mFragments[2] = ShowEverybodyFragment.newInstance();
        mFragments[3] = MeFragment.newInstance();
        setDefaultFragment(curIndex);
    }

    private void initBottomBar() {
        mBottomNavigationBar.clearAll();
        mBottomNavigationBar.setMode(BottomNavigationBar.MODE_FIXED);
        mBottomNavigationBar.setBarBackgroundColor(R.color.white);
        mBottomNavigationBar.setBackgroundStyle(BottomNavigationBar.BACKGROUND_STYLE_STATIC);
        mBottomNavigationBar.setActiveColor(R.color.color_home_tab_active).setInActiveColor(R.color.color_home_tab_inactive);

        mBottomNavigationBar
                .addItem(new BottomNavigationItem(R.drawable.ic_tab_home, R.string.bottom_menu_home))
                .addItem(new BottomNavigationItem(R.drawable.ic_tab_dynamic, R.string.bottom_menu_dynamic))
                .addItem(new BottomNavigationItem(R.drawable.ic_tab_welook, R.string.bottom_menu_welook))
                .addItem(new BottomNavigationItem(R.drawable.ic_tab_me, R.string.bottom_menu_me)).initialise();
        mBottomNavigationBar.setTabSelectedListener(this);
    }

    private void setDefaultFragment(int position) {
        FragmentManager fm = getSupportFragmentManager();
        FragmentTransaction transaction = fm.beginTransaction();
        transaction.add(R.id.content_layout, mFragments[position]);
        transaction.commit();
    }

    @Override
    public void onTabSelected(int position) {
        if (position == 3) {
            if (App.getInstance().isUserLogin()) {
                beforeIndex = position;
                showHideFragment(curIndex = position);
            } else {
                curIndex = position;
                Intent intent = new Intent(MainActivity.this, LoginActivity.class);
                startActivityForResult(intent, ConstantManager.REQUEST_LOGIN_CODE);
            }
        } else {
            beforeIndex = position;
            showHideFragment(curIndex = position);
        }
    }

    private void showHideFragment(int position) {
        try {
            if (mFragments != null) {
                if (position < mFragments.length) {
                    FragmentTransaction ft = mFragmentManager.beginTransaction();
                    //当前的fragment
                    Fragment from = mFragmentManager.findFragmentById(R.id.content_layout);
                    //点击即将跳转的fragment
                    Fragment fragment = mFragments[position];
                    if (fragment.isAdded()) {
                        // 隐藏当前的fragment，显示下一个
                        ft.hide(from).show(fragment);
                    } else {
                        ft.hide(from).add(R.id.content_layout, fragment);
                    }
                    ft.commitAllowingStateLoss();
                }
            }
        } catch (Exception e) {
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == ConstantManager.REQUEST_LOGIN_CODE) {
            if (resultCode == RESULT_OK) {
                mBottomNavigationBar.selectTab(curIndex);
                EventBus.getDefault().post(new LoadUserInfoEvent());
            } else {
                mBottomNavigationBar.selectTab(beforeIndex);
            }
        }
    }

    @Override
    public void onTabUnselected(int position) {
        if (mFragments != null) {
            if (position < mFragments.length) {
                FragmentManager fm = getSupportFragmentManager();
                FragmentTransaction ft = fm.beginTransaction();
                Fragment fragment = mFragments[position];
                // 隐藏当前的fragment
                ft.hide(fragment);
                ft.commitAllowingStateLoss();
            }
        }
    }

    @Override
    public void onTabReselected(int position) {
    }

    @Override
    protected void onDestroy() {
        // 注销
        EventBus.getDefault().unregister(this);
        super.onDestroy();
        curIndex = 0;
        beforeIndex = 0;
        /*if (DataSupport.findFirst(UserAccount.class) != null) {
            ContentValues values = new ContentValues();
            values.put("loginStatus", ConstantManager.LOGIN_OUT);
            DataSupport.updateAll(UserAccount.class, values);
        }*/
    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    /**
     * token失效，重新登录
     */
    @Subscriber(tag = ConstantManager.RELOGIN_TAG)
    private void reLogin(int code) {
        LogUtils.a("---------------------reLogin:" + code);
        if (code == ConstantManager.RELOGIN_CODE_EXPIRED) {
            ToastUtils.showLong(getString(R.string.txt_relogin));
        }else if(code == ConstantManager.RELOGIN_CODE_FORBIDDEN){
            ToastUtils.showLong(getString(R.string.txt_relogin_forbidden));
        }
        Intent intent = new Intent(this, LoginActivity.class);
        intent.putExtra(LoginActivity.EXTRA_LOGINED_SHOW_PAGE, ConstantManager.MAIN_PAGE_INDEX);
        startActivity(intent);
        UserAccount account = App.getInstance().getCurrentAccount();
        account.setPassword("");
        account.setToken("");
        account.setLoginStatus(ConstantManager.LOGIN_OUT);
        App.getInstance().updateAccount(account);
        App.getInstance().finishAllActivity();//关闭所有Activity
    }
}